<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-select v-model="queryParams.roleName">
          <el-option label="系统管理员" value="系统管理员"></el-option>
          <el-option label="超级管理员" value="超级管理员"></el-option>
          <el-option label="普通用户" value="普通用户"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          clearable
        >
          <el-option label="正常" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- =========================================== -->
    <el-row :gutter="10" style="margin-bottom: 20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-upload
          action="#"
          multiple
          :show-file-list="false"
          :http-request="batchExcel"
        >
          <el-button type="warning" plain icon="el-icon-download" size="mini"
            >导入</el-button
          >
        </el-upload>
      </el-col>
      <el-col :span="1.5"
        ><el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="templateDow"
          >模板下载</el-button
        ></el-col
      >
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <!-- 表格数据 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="loading"
      border
      style="margin-bottom: 20px"
    >
      <el-table-column
        label="用户名"
        prop="username"
        align="center"
      ></el-table-column>
      <el-table-column
        label="姓名"
        prop="name"
        align="center"
      ></el-table-column>
      <el-table-column
        label="用户角色名称"
        prop="roleId"
        align="center"
      ></el-table-column>
      <el-table-column label="用户状态" prop="status" align="center">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="changeStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="邮箱"
        prop="email"
        align="center"
      ></el-table-column>
      <el-table-column
        label="手机号"
        prop="telephone"
        align="center"
      ></el-table-column>

      <el-table-column
        label="数据权限"
        prop="dataScope"
        align="center"
      ></el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <template slot-scope="scope">
          <el-button size="mini" @click="updateRole(scope.row)"
            >修改权限</el-button
          >
          <el-button size="mini" type="danger" @click="deleteUser(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页v-show="total > 0" -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageCurrent"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next"
      :total="total"
    ></el-pagination>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      @close="closeVisible"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="form.telephone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <!-- <el-form-item label="用户状态" prop="status">
                    <el-select v-model="form.status">
                        <el-option label="正常" value="0"></el-option>
                        <el-option label="禁用" value="1"></el-option>
                    </el-select>
                </el-form-item>-->
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" @change="roleIdChange">
            <el-option label="系统管理员" value="1"></el-option>
            <el-option label="超级管理员" value="2"></el-option>
            <el-option label="普通用户" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </div>
    </el-dialog>
    <!-- 修改权限 -->
    <el-dialog
      title="修改权限"
      :visible.sync="roleDialog"
      width="500px"
      append-to-body
    >
      <el-form :model="form">
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" @change="roleIdChange">
            <el-option label="系统管理员" value="1"></el-option>
            <el-option label="超级管理员" value="2"></el-option>
            <el-option label="普通用户" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="addRole">确 定</el-button>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUser,
  saveUser,
  changeRole,
  update,
  saveExcel,
  deleteUser,
  excelTemplate,
} from "@/api/user";
export default {
  data() {
    // 自定义邮箱校验
    const validateEmail = (rule, value) => {
      let emailReg =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (!value) {
        return Promise.reject("邮箱不能为空");
      } else if (!emailReg.test(value)) {
        return Promise.reject("邮箱格式不正确");
      } else {
        return Promise.resolve();
      }
    };
    // 自定义手机号校验
    const validPhone = (rule, value) => {
      let phoneReg =
        /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (!value) {
        return Promise.reject("手机号不能为空");
      }
      if (!phoneReg.test(value)) {
        return Promise.reject("手机号格式不正确");
      } else {
        return Promise.resolve();
      }
    };
    return {
      tableData: [],
      loading: false,
      // 表格条数
      total: undefined,
      queryParams: {
        pageCurrent: 1,
        pageSize: 10,
        name: undefined,
        roleName: undefined,
        status: undefined,
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      form: {
        roleId: undefined,
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        roleId: [
          { required: true, message: "请选择角色名称", trigger: "blur" },
        ],
        telephone: [{ required: true, validator: validPhone }],
        email: [{ required: true, validator: validateEmail }],
      },
      roleDialog: false,
      roleId: "",
      userId: "",
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 获取表格数据
    getList() {
      this.loading = true;
      getUser(this.queryParams).then((res) => {
        if (res.code == 200) {
          console.log(res);
          this.loading = false;
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    roleIdChange() {
      console.log(this.form.roleId);
      this.form.dataScope = this.form.roleId;
    },
    // 分页==========================================================
    handleSizeChange(pageSizeVal) {
      this.queryParams.pageSize = pageSizeVal;
      this.getList();
    },
    handleCurrentChange(pageCurrentVal) {
      this.queryParams.pageCurrent = pageCurrentVal;
      this.getList();
    },
    // 清空表单
    restForm() {
      this.form = {
        name: undefined,
        password: undefined,
        roleName: undefined,
        telephone: undefined,
        email: undefined,
      };
    },

    // 模板下载
    async templateDow() {
      await excelTemplate().then((res) => {
        window.open(res.data.url);
      });
    },
    // 删除
    async deleteUser(row) {
      const confirm = await this.$confirm(
        "此操作将永久删除, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirm !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // 确定删除
      deleteUser({ id: row.id }).then((res) => {
        if (res.code !== 200) {
          this.$message.error("删除失败");
        } else {
          this.$message.success("删除成功");
          this.getList();
        }
      });
    },
    // 新增
    handleAdd() {
      this.restForm();
      this.id = "";
      this.open = true;
      this.title = "添加";
    },
    // 表单提交
    submitForm() {
      // 校验表单
      this.$refs.form.validate((valid) => {
        if (valid) {
          saveUser(this.form)
            .then((res) => {
              if (res.code == 200) {
                console.log(res);
                this.open = false;
                this.getList();
                this.$message.success("添加成功");
              }
            })
            .catch(() => {
              this.open = false;
            });
        }
      });
    },
    // 关闭弹窗
    closeVisible() {
      this.restForm();
      this.$refs.form.resetFields();
      this.open = false;
    },
    // 修改权限
    updateRole(row) {
      this.roleDialog = true;
      this.form.roleId = row.roleId;
      this.form.dataScope = row.dataScope;
      this.userId = row.id;
    },
    addRole() {
      changeRole({
        roleId: this.form.roleId,
        userId: this.userId,
        dataScope: this.form.dataScope,
      }).then((res) => {
        if (res.code == 200) {
          this.roleDialog = false;
          this.getList();
          this.$message.success(res.msg);
        }
      });
    },
    // 修改用户状态
    changeStatus(row) {
      update({ id: row.id, status: row.status }).then((res) => {
        console.log(res);
        this.getList();
      });
    },
    // 重置按钮
    resetForm() {
      this.restForm();
      this.$refs.form.resetFields();
    },
    // 导入
    batchExcel(excel) {
      // 发请求
      const obj = new FormData();
      obj.append("file", excel.file);
      saveExcel(obj)
        .then((res) => {
          if (res.code == "200") {
            console.log(res);
            this.$message.success(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
          return;
        });
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageCurrent = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.getList();
    },
  },
};
</script>
